package br.com.insejeccg.util.bean.convert;


@SuppressWarnings("unchecked")
public final class BooleanConverter implements ConverterToString {
    /**
     * The default value specified to our Constructor, if any.
     */
    private Object defaultValue = null;
    private String trueValue;
    private String falseValue;
    private org.apache.commons.beanutils.converters.BooleanConverter booleanConverter;

    public BooleanConverter(String trueValue, Object defaultValue) {
        this(trueValue, null, defaultValue);
    }

    public BooleanConverter(String trueValue, String falseValue,
        Object defaultValue) {
        super();
        booleanConverter = new org.apache.commons.beanutils.converters.BooleanConverter(defaultValue);
        this.trueValue = trueValue;
        this.falseValue = falseValue;
        this.defaultValue = defaultValue;
    }

    public Object convert(Class type, Object value) {
        if (value == null) {
            return (defaultValue);
        }

        if (value instanceof Boolean) {
            return (value);
        }

        try {
            String stringValue = value.toString();

            if (trueValue.equals(stringValue)) {
                return (Boolean.TRUE);
            } else if ((this.falseValue != null) &&
                    falseValue.equals(stringValue)) {
                return (Boolean.FALSE);
            } else {
                return booleanConverter.convert(type, value);
            }
        } catch (ClassCastException e) {
            return (defaultValue);
        }
    }

    public String convertToString(Object value) {
        if ((value != null) && value instanceof Boolean) {
            try {
                Boolean b = (Boolean) value;

                if (b.booleanValue()) {
                    return trueValue;
                } else {
                    return falseValue;
                }
            } catch (Exception e) {
                return "";
            }
        }

        return "";
    }
}
